﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace Natty.NetCore.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TokenController : ControllerBase
    {
       
        private readonly ILogger<TokenController> _logger;

        public TokenController(ILogger<TokenController> logger)
        {
            _logger = logger;
        }

        [AllowAnonymous]
        [HttpGet, Route("/GetToken")]
        public ActionResult<string> GetToken()
        {
            //DateTime utc = DateTime.UtcNow;
            var claims = new List<Claim>
           {
               new Claim(JwtRegisteredClaimNames.Jti,"1"),//编号
               new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//签发时间
               new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//生效时间
                // 过期时间 100秒
               new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddDays(0.5)).ToUnixTimeSeconds()}"),
               new Claim(JwtRegisteredClaimNames.Iss,"API"), // 签发者
               new Claim(JwtRegisteredClaimNames.Aud,"User") // 接收者
           };


            // 密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("111111111111111111111111111111111111111111111111111"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var tokenHandler = new JwtSecurityTokenHandler();

            JwtSecurityToken jwt = new JwtSecurityToken(

                claims: claims,// 声明的集合
                //expires: DateTime.Now.AddSeconds(36), // token的有效时间
                signingCredentials: creds
                );
            var handler = new JwtSecurityTokenHandler();
            // 生成 jwt字符串
            var strJWT = handler.WriteToken(jwt);
            return Ok(strJWT);
        }
    }
}
